package cn.alm.allinoneboot.interceptor;

import cn.alm.allinoneboot.utils.JedisPoolUtil;
import cn.alm.allinoneboot.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 并未启用
//@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Access-Token");
        if (!StringUtils.hasText(token)) {
            throw new Exception("登录失效");
        }
        Claims claims = JwtUtil.parseJwt(token);
        String subject = claims.getSubject();
        Jedis jedis = JedisPoolUtil.getJedisPoolInstance().getResource();
        String s = jedis.get(subject);
        if (s == null) {
            throw new Exception("登录失效");
        }
        if (!s.equals(token)) {
            throw new Exception("登录失效");
        }
        jedis.expire(subject, 3600);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
